package br.ufal.ic.fracao.agent.resolution.operation.simplification;

import java.io.IOException;

import org.jdom.JDOMException;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;


public class SimplificationAgent extends Agent{

	@Override
	protected void setup() {
		this.yellowPagesRegistry("SimplificationAgent", "Simplification");
		this.addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				ACLMessage message = receive();
				if(message != null){
					String messageContent = message.getContent();
					String[] messageContentSplit = messageContent.split("/");
					
					String solution = messageContent;
					
					if(messageContentSplit.length == 2){
						int n1 = 0;
						int d1 = 0;
						
						n1 = Integer.parseInt(messageContentSplit[0]);
						d1 = Integer.parseInt(messageContentSplit[1]);
											
						SimplificationAdapter adapter = new SimplificationAdapter();
						
						try {
							solution = adapter.getSolution(n1, d1);
						} catch (IOException e) {
							e.printStackTrace();
						} catch (JDOMException e) {
							e.printStackTrace();
						}
					}	
					
					ACLMessage reply = message.createReply();
					reply.setContent("SimplificationAgent:" + solution);
					send(reply);
					
				}
			}
		});
	}
	
	public boolean yellowPagesRegistry(String name, String service){
		DFAgentDescription descritorDeServicosDeUmAgente = new DFAgentDescription();
		ServiceDescription descricaoDeUmServico = new ServiceDescription();
		descricaoDeUmServico.setName(name);
		descricaoDeUmServico.setType(service);
		descritorDeServicosDeUmAgente.addServices(descricaoDeUmServico);
		try{
			DFService.register(this,descritorDeServicosDeUmAgente);
			return true;
		}catch(FIPAException e){
			return false;
		}		
	}
	
}
